<template>
  <div class="login" ref="login">
    <div class="dataContent">
      <div class="title">欢迎登录外包考勤系统</div>
      <!-- 表单区域 -->
      <van-form ref="loginFormRef" @submit="onSubmit" @failed="onFailed">
        <!-- 手机号 -->
        <van-field
          v-model="infoFrom.mobile"
          name="mobile"
          placeholder="请输入手机号"
          clearable
          :border="false"
          autocomplete="off"
          :rules="[
            { required: true },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号格式错误！' }
          ]"
        />
        <!-- 短信验证码 -->
        <van-field
          v-model="infoFrom.code"
          name="code"
          center
          clearable
          :border="false"
          placeholder="请输入短信验证码"
          label-width="20px"
          maxlength="6"
          :rules="[
            { required: true },
            { pattern: /^\d{6}$/, message: '短信验证码格式错误！' }
          ]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="median"
              :class="[btnState ? 'btnOne' : 'btnTwo']"
              @click="SendCode"
              >{{ SendVCode }}</van-button
            >
          </template>
        </van-field>
        <!-- 登录 -->
        <div style="" class="startLogin">
          <van-button
            block
            type="info"
            native-type="submit"
            :class="[Lstart ? 'opaque' : 'pellucid']"
            :disabled="!Lstart"
            >登录</van-button
          >
        </div>
      </van-form>
    </div>
    <div class="banbenhao">V0.1.12</div>
  </div>
</template>
<script>
// import { getRsaCode } from '@/RSA'
import backMixin from '@/backMixin'
export default {
  name: 'login',
  mixins: [backMixin],
  data() {
    return {
      version: '',
      // 短信验证码提示文字
      SendVCode: '发送验证码',
      // 绑定的信息
      infoFrom: {
        mobile: '',
        code: '' // 短信验证码
      },
      btnState: true,
      formcheck: false //表单是否通过
    }
  },
  created() {
    // this.getUserName()
    let aaa = JSON.parse(window.localStorage.getItem('attendance-records'))
    if (aaa && aaa.role == 1) {
      this.$router.push('/workbench')
    } else if (aaa && aaa.role == 0) {
      this.$router.push('/outsourcingNewApply')
    } else if (aaa && aaa.role == 2) {
      this.$router.push('/settingPage')
    }
  },
  methods: {
    // 显示成功登录的用户.
    // getUserName() {
    // let mobile = JSON.parse(
    //   window.localStorage.getItem('attendance-records')
    // ).mobile // 取缓存中的mobile字段
    // this.infoFrom.mobile = mobile || '' // 判断mobile是否存在，不存在赋值为空
    // },
    // 密码输入框聚焦事件
    holdBack() {
      // document.activeElement.blur()
    },

    // 点击发送短信验证码时触发
    SendCode() {
      let params = {
        mobile: this.infoFrom.mobile
      }
      // console.log('短信验证码接口,查看传入参数', params)
      this.$axios({
        url: '/msg-code',
        method: 'get',
        params: params
      })
        .then(res => {
          console.log('res接口返回啥子', res)
          // 正确的话
          this.toast('success', '发送成功')
          // 按钮置灰并倒计时
          this.countDown()
          // 不正确的话 路由拦截器直接拦截
        })
        .catch(error => {
          return this.toast('fail', error.message)
        })
    },

    //点登陆验证表单通过情况
    onFailed(errorInfo) {
      console.log('failed', errorInfo)

      if (errorInfo) {
        this.formcheck = false
      }
    },
    onSubmit(val) {
      console.log('提交', val)
      this.formcheck = true
      if (this.formcheck) {
        console.log('else')
        let params = {
          ...this.infoFrom
        }
        console.log('登录接口查看传入参数:', params, this.infoFrom)

        // 请求登录接口
        this.$axios({
          url: '/attendance-api/employee-sms-login',
          method: 'POST',
          data: params
        })
          .then(res => {
            console.log('登录接口', res)
            if (res) {
              if (res.data.Status == 'success') {
                this.toast('success', res.data.Message)
                // 给登录成功的用户打一个标记，防止不小心退出应用，再进又需登录
                window.localStorage.setItem('loginFlag', '1')
                let info = res.data.Object
                // 将用户权限、ID、邮箱、部门、手机号、token存起来
                window.localStorage.setItem(
                  'attendance-records',
                  JSON.stringify({
                    role: info.role,
                    id: info.ID,
                    email: info.Email,
                    deptId: info.DeptID,
                    mobile: info.Mobile,
                    token: info.token,
                    name: info.Name,
                    code: this.infoFrom.code
                  })
                )
                // 将申请状态存储起来
                this.$axios({
                  url: '/attendance-api/status-types',
                  method: 'get',
                  params: {}
                }).then(res => {
                  let statusName = res.data.Object
                  window.localStorage.setItem(
                    'attendance-records_status',
                    JSON.stringify(statusName)
                  )
                  //role 0外包，1部门主管，2HR
                  if (info.role == 1) {
                    this.$router.push({
                      name: 'workbench'
                    })
                  } else if (info.role == 2) {
                    this.$router.push({
                      name: 'settingPage'
                    })
                  } else {
                    this.$router.push({
                      name: 'outsourcingNewApply'
                    })
                  }
                })
              } else {
                console.log(res)
                this.toast('fail', res.Message)
              }
            } else {
              console.log(res)
            }
          })
          .catch(error => {
            console.log(error)
            this.toast('fail', error.Message)
          })
      }
    },

    // 倒计时并将按钮置灰
    countDown() {
      this.btnState = false
      let nums = 60
      this.SendVCode = nums + 's'
      let _this = this
      let t = setInterval(() => {
        _this.SendVCode = (nums -= 1) + 's'
        if (nums === 0) {
          // 倒数完成清除定时器
          clearInterval(t)
          _this.btnState = true
          _this.SendVCode = '发送验证码'
        }
      }, 1000)
    },
    // 轻提示封装
    toast(state, message) {
      if (state === 'success') {
        return this.$toast.success({
          duration: 1000, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          message,
          className: 'van-gradual',
          getContainer: () => {
            return document.querySelector('#app')
          }
        })
      } else {
        return this.$toast.fail({
          duration: 1000, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          message,
          className: 'van-gradual',
          getContainer: () => {
            return document.querySelector('#app')
          }
        })
      }
    },
    // 返回
    onClickLeft() {
      this.finishInApp()
    },
    // 判断当前系统是否为iOS系统
    IsIOS() {
      if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        return true
      } else {
        return false
      }
    },
    // 判断当前系统是否安卓系统
    IsAndroid() {
      if (/(Android|Adr)/i.test(navigator.userAgent)) {
        return true
      } else {
        return false
      }
    },
    async finishInApp() {
      this.$router.push({ name: 'login' })
      // if (this.IsIOS()) {
      //   console.log('IOS >>>>> ', window.webkit, window.webkit.messageHandlers)
      //   window.webkit.messageHandlers.LinkToDfitcNativeFunction.postMessage(
      //     '9918'
      //   )
      // } else if (this.IsAndroid()) {
      //   window.smartinfo.LinkToDfitcNativeFunction('9918')
      // }
    }
  },
  computed: {
    Lstart() {
      if (
        this.infoFrom.mobile !== '' &&
        this.infoFrom.validationPhoneCode !== ''
      ) {
        return true
      } else {
        return false
      }
    },
    median() {
      if (this.infoFrom.mobile !== '' && this.btnState) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>
<style lang="less" scoped>
.login {
  margin: 0;
  padding: 0;
  .banbenhao {
    color: #bbb;
    margin-top: 200px;
  }
  .van-nav-bar__arrow {
    font-size: 18px;
    color: #000;
  }
  .van-nav-bar__content {
    .van-nav-bar__title {
      font-size: 18px;
    }
  }
  .dataContent {
    margin-top: 46px;
  }
  .title {
    width: 207px;
    height: 57px;
    margin-left: 30px;
    margin-top: 130px;
    margin-bottom: 36px;
    font-size: 16px;
    text-align: left;
    color: #323232;
    // font-weight: 600;
    margin-bottom: 6px;
  }

  .van-form {
    padding: 0 30px;
    box-sizing: border-box;
    .van-field {
      width: 100%;
      padding: 20px 0 8px 0;
      border-bottom: 1px solid #e2e2e2;
    }
    .van-field__control {
      color: #323232;
    }
    .van-cell--center {
      padding-bottom: 3px;
    }
    .btnOne {
      border: none;
      background: #fff;
      color: #2274f9;
      font-size: 14px;
      padding-right: 1px !important;
    }
    .btnTwo {
      border: none;
      background: #fff;
      color: rgb(161, 161, 162);
      font-size: 18px;
      padding-right: 1px !important;
    }
    .startLogin {
      margin-top: 40px;
      .van-button--disabled {
        border-radius: 10px;
      }
    }
    .opaque {
      opacity: 1;
      border-radius: 10px;
    }
    .pellucid {
      opacity: 0.5;
      border-radius: 10px;
    }
  }
}
</style>
